package org.qiandaosystem.qiandaosystemsource.service;

import com.google.zxing.WriterException;
import lombok.RequiredArgsConstructor;
import org.qiandaosystem.qiandaosystemsource.common.ApiResponse;
import org.qiandaosystem.qiandaosystemsource.entity.SignActivity;
import org.qiandaosystem.qiandaosystemsource.entity.SignRecord;
import org.qiandaosystem.qiandaosystemsource.entity.Teacher;
import org.qiandaosystem.qiandaosystemsource.entity.User;
import org.qiandaosystem.qiandaosystemsource.mapper.SignActivityMapper;
import org.qiandaosystem.qiandaosystemsource.mapper.SignRecordMapper;
import org.qiandaosystem.qiandaosystemsource.mapper.TeacherMapper;
import org.qiandaosystem.qiandaosystemsource.mapper.UserMapper;
import org.qiandaosystem.qiandaosystemsource.util.JwtUtil;
import org.qiandaosystem.qiandaosystemsource.util.QrCodeUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class QrCodeSignService {
    
    private final SignActivityMapper signActivityMapper;
    private final SignRecordMapper signRecordMapper;
    private final UserMapper userMapper;
    private final TeacherMapper teacherMapper;
    private final JwtUtil jwtUtil;
    private final QrCodeUtil qrCodeUtil;
    
    @Transactional
    public ApiResponse<?> createQrCodeSignActivity(String token, LocalDateTime startTime, LocalDateTime endTime) {
        String username = jwtUtil.extractUsername(token);
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        
        Teacher teacher = teacherMapper.findByUserId(user.getId());
        if (teacher == null) {
            return ApiResponse.error("只有教师才能创建签到活动");
        }
        
        SignActivity activity = new SignActivity();
        activity.setTeacherId(teacher.getUserId());
        activity.setType(SignActivity.SignType.qr);
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        activity.setSecret(UUID.randomUUID().toString());
        activity.setDeleted(false);
        
        signActivityMapper.insert(activity);
        
        return ApiResponse.success("二维码签到活动创建成功");
    }
    
    public ApiResponse<?> getQrCode(String token, Integer activityId) {
        String username = jwtUtil.extractUsername(token);
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        
        Teacher teacher = teacherMapper.findByUserId(user.getId());
        if (teacher == null) {
            return ApiResponse.error("只有教师才能获取签到二维码");
        }
        
        SignActivity activity = signActivityMapper.findById(activityId);
        if (activity == null || activity.getDeleted()) {
            return ApiResponse.error("签到活动不存在");
        }
        
        if (!activity.getTeacherId().equals(teacher.getUserId())) {
            return ApiResponse.error("无权访问此签到活动");
        }
        
        if (!activity.getType().equals(SignActivity.SignType.qr)) {
            return ApiResponse.error("该活动不是二维码签到活动");
        }
        
        // 更新二维码密钥
        activity.setSecret(UUID.randomUUID().toString());
        signActivityMapper.update(activity);
        
        try {
            String content = qrCodeUtil.generateQrCodeContent(
                activityId, 
                activity.getSecret(), 
                System.currentTimeMillis()
            );
            byte[] qrCodeImage = qrCodeUtil.generateQrCode(content, 300, 300);
            String base64Image = Base64.getEncoder().encodeToString(qrCodeImage);
            
            return ApiResponse.success(base64Image);
        } catch (WriterException | IOException e) {
            return ApiResponse.error("二维码生成失败");
        }
    }
    
    @Transactional
    public ApiResponse<?> verifyQrCode(String token, String qrCodeContent) {
        String username = jwtUtil.extractUsername(token);
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        
        String[] parts = qrCodeContent.split(":");
        if (parts.length != 3) {
            return ApiResponse.error("无效的二维码");
        }
        
        Integer activityId = Integer.parseInt(parts[0]);
        String secret = parts[1];
        long timestamp = Long.parseLong(parts[2]);
        
        SignActivity activity = signActivityMapper.findById(activityId);
        if (activity == null || activity.getDeleted()) {
            return ApiResponse.error("签到活动不存在");
        }
        
        if (!activity.getType().equals(SignActivity.SignType.qr)) {
            return ApiResponse.error("该活动不是二维码签到活动");
        }
        
        if (activity.getEndTime().isBefore(LocalDateTime.now())) {
            return ApiResponse.error("签到活动已结束");
        }
        
        if (!activity.getSecret().equals(secret)) {
            return ApiResponse.error("二维码已过期，请重新扫描");
        }
        
        // 检查是否已经签到
        SignRecord existingRecord = signRecordMapper.findByActivityIdAndStudentId(activityId, user.getId());
        if (existingRecord != null && existingRecord.getStatus() == SignRecord.SignStatus.success) {
            return ApiResponse.error("您已经签到过了");
        }
        
        // 创建签到记录
        SignRecord record = new SignRecord();
        record.setActivityId(activityId);
        record.setStudentId(user.getId());
        record.setSignTime(LocalDateTime.now());
        record.setStatus(SignRecord.SignStatus.success);
        record.setDetail("二维码签到");
        
        signRecordMapper.insert(record);
        
        return ApiResponse.success("签到成功");
    }
} 